from fastapi import APIRouter, Depends, HTTPException, Query
from typing import List, Optional, Dict

from app.core.deps import get_current_active_user
from app.models.models import User, Permission
from app.schemas.permission import PermissionCreate, PermissionUpdate, PermissionOut
from app.schemas.base import ResponseBase, PageResponseBase, PageInfo

router = APIRouter()

@router.get("/", response_model=PageResponseBase[List[PermissionOut]])
async def get_permissions(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页条数"),
    name: Optional[str] = Query(None, description="权限名称"),
    code: Optional[str] = Query(None, description="权限编码"),
    type: Optional[str] = Query(None, description="权限类型"),
    status: Optional[bool] = Query(None, description="状态"),
    _: User = Depends(get_current_active_user)
):
    """获取权限列表"""
    # 构建查询条件
    query = {}
    if name:
        query["name__contains"] = name
    if code:
        query["code__contains"] = code
    if type:
        query["type"] = type
    if status is not None:
        query["status"] = status
    
    # 查询总数
    total = await Permission.filter(**query).count()
    
    # 分页查询
    permissions = await Permission.filter(**query).offset((page - 1) * page_size).limit(page_size).all()
    
    # 构建权限列表
    permission_list = []
    for permission in permissions:
        # 构建权限信息
        permission_data = {
            "id": permission.id,
            "name": permission.name,
            "code": permission.code,
            "type": permission.type,
            "parent_id": permission.parent_id,
            "path": permission.path,
            "component": permission.component,
            "icon": permission.icon,
            "sort": permission.sort,
            "status": permission.status,
            "children": [],
            "created_at": permission.created_at,
            "updated_at": permission.updated_at
        }
        
        permission_list.append(PermissionOut(**permission_data))
    
    # 构建分页信息
    page_info = PageInfo(page=page, page_size=page_size, total=total)
    
    return PageResponseBase[List[PermissionOut]](
        data=permission_list,
        page_info=page_info
    )

@router.get("/tree", response_model=ResponseBase[List[PermissionOut]])
async def get_permission_tree(
    type: Optional[str] = Query(None, description="权限类型"),
    status: Optional[bool] = Query(None, description="状态"),
    _: User = Depends(get_current_active_user)
):
    """获取权限树形结构"""
    # 构建查询条件
    query = {}
    if type:
        query["type"] = type
    if status is not None:
        query["status"] = status
    
    # 查询所有权限
    permissions = await Permission.filter(**query).all()
    
    # 构建权限字典
    permission_dict: Dict[int, PermissionOut] = {}
    for permission in permissions:
        # 构建权限信息
        permission_data = {
            "id": permission.id,
            "name": permission.name,
            "code": permission.code,
            "type": permission.type,
            "parent_id": permission.parent_id,
            "path": permission.path,
            "component": permission.component,
            "icon": permission.icon,
            "sort": permission.sort,
            "status": permission.status,
            "children": [],
            "created_at": permission.created_at,
            "updated_at": permission.updated_at
        }
        
        permission_dict[permission.id] = PermissionOut(**permission_data)
    
    # 构建树形结构
    tree = []
    for permission_id, permission in permission_dict.items():
        if permission.parent_id is None:
            # 顶级权限
            tree.append(permission)
        else:
            # 子权限
            if permission.parent_id in permission_dict:
                permission_dict[permission.parent_id].children.append(permission)
    
    # 按排序字段排序
    tree.sort(key=lambda x: x.sort)
    for permission in permission_dict.values():
        permission.children.sort(key=lambda x: x.sort)
    
    return ResponseBase[List[PermissionOut]](data=tree)

@router.post("/", response_model=ResponseBase[PermissionOut])
async def create_permission(
    permission_in: PermissionCreate,
    _: User = Depends(get_current_active_user)
):
    """创建权限"""
    # 检查权限编码是否已存在
    if await Permission.filter(code=permission_in.code).exists():
        raise HTTPException(status_code=400, detail="权限编码已存在")
    
    # 检查父权限是否存在
    if permission_in.parent_id and not await Permission.filter(id=permission_in.parent_id).exists():
        raise HTTPException(status_code=400, detail="父权限不存在")
    
    # 创建权限
    permission = await Permission.create(
        name=permission_in.name,
        code=permission_in.code,
        type=permission_in.type,
        parent_id=permission_in.parent_id,
        path=permission_in.path,
        component=permission_in.component,
        icon=permission_in.icon,
        sort=permission_in.sort,
        status=permission_in.status
    )
    
    # 构建权限信息
    permission_data = {
        "id": permission.id,
        "name": permission.name,
        "code": permission.code,
        "type": permission.type,
        "parent_id": permission.parent_id,
        "path": permission.path,
        "component": permission.component,
        "icon": permission.icon,
        "sort": permission.sort,
        "status": permission.status,
        "children": [],
        "created_at": permission.created_at,
        "updated_at": permission.updated_at
    }
    
    return ResponseBase[PermissionOut](data=PermissionOut(**permission_data))

@router.get("/{permission_id}", response_model=ResponseBase[PermissionOut])
async def get_permission(
    permission_id: int,
    _: User = Depends(get_current_active_user)
):
    """获取权限详情"""
    permission = await Permission.filter(id=permission_id).first()
    if not permission:
        raise HTTPException(status_code=404, detail="权限不存在")
    
    # 构建权限信息
    permission_data = {
        "id": permission.id,
        "name": permission.name,
        "code": permission.code,
        "type": permission.type,
        "parent_id": permission.parent_id,
        "path": permission.path,
        "component": permission.component,
        "icon": permission.icon,
        "sort": permission.sort,
        "status": permission.status,
        "children": [],
        "created_at": permission.created_at,
        "updated_at": permission.updated_at
    }
    
    return ResponseBase[PermissionOut](data=PermissionOut(**permission_data))

@router.put("/{permission_id}", response_model=ResponseBase[PermissionOut])
async def update_permission(
    permission_id: int,
    permission_in: PermissionUpdate,
    _: User = Depends(get_current_active_user)
):
    """更新权限"""
    permission = await Permission.filter(id=permission_id).first()
    if not permission:
        raise HTTPException(status_code=404, detail="权限不存在")
    
    # 检查权限编码是否已存在
    if permission_in.code and permission_in.code != permission.code:
        if await Permission.filter(code=permission_in.code).exists():
            raise HTTPException(status_code=400, detail="权限编码已存在")
    
    # 检查父权限是否存在
    if permission_in.parent_id and permission_in.parent_id != permission.parent_id:
        if not await Permission.filter(id=permission_in.parent_id).exists():
            raise HTTPException(status_code=400, detail="父权限不存在")
        
        # 检查是否将权限设置为自己的子权限
        if permission_in.parent_id == permission.id:
            raise HTTPException(status_code=400, detail="不能将权限设置为自己的子权限")
        
        # 检查是否将权限设置为自己的子权限的子权限
        child_ids = await get_child_permission_ids(permission.id)
        if permission_in.parent_id in child_ids:
            raise HTTPException(status_code=400, detail="不能将权限设置为自己的子权限的子权限")
    
    # 更新权限信息
    update_data = permission_in.dict(exclude_unset=True)
    
    # 更新权限
    await permission.update_from_dict(update_data)
    await permission.save()
    
    # 构建权限信息
    permission_data = {
        "id": permission.id,
        "name": permission.name,
        "code": permission.code,
        "type": permission.type,
        "parent_id": permission.parent_id,
        "path": permission.path,
        "component": permission.component,
        "icon": permission.icon,
        "sort": permission.sort,
        "status": permission.status,
        "children": [],
        "created_at": permission.created_at,
        "updated_at": permission.updated_at
    }
    
    return ResponseBase[PermissionOut](data=PermissionOut(**permission_data))

@router.delete("/{permission_id}", response_model=ResponseBase)
async def delete_permission(
    permission_id: int,
    _: User = Depends(get_current_active_user)
):
    """删除权限"""
    permission = await Permission.filter(id=permission_id).first()
    if not permission:
        raise HTTPException(status_code=404, detail="权限不存在")
    
    # 检查权限是否有子权限
    if await Permission.filter(parent_id=permission.id).exists():
        raise HTTPException(status_code=400, detail="权限下有子权限，无法删除")
    
    # 检查权限是否被角色使用
    if await permission.permission_roles.exists():
        raise HTTPException(status_code=400, detail="权限已被角色使用，无法删除")
    
    # 删除权限
    await permission.delete()
    
    return ResponseBase()

async def get_child_permission_ids(permission_id: int) -> List[int]:
    """获取子权限ID列表"""
    child_ids = []
    
    # 获取直接子权限
    children = await Permission.filter(parent_id=permission_id).all()
    for child in children:
        child_ids.append(child.id)
        # 递归获取子权限的子权限
        child_child_ids = await get_child_permission_ids(child.id)
        child_ids.extend(child_child_ids)
    
    return child_ids